<?php

namespace app\admin\controller;

use app\admin\validate\CheckArticle;
use think\exception\ValidateException;

class Article extends Base
{
    protected $mod;

    protected function initialize()
    {
        parent::initialize();
        $this->mod = new \app\admin\model\Article();
    }


    public function index(String $keyword = '', int $limit=10,int $page=1)
    {
        $map = [];
        if ($keyword) {
            $map[] = ['title', 'like', "%$keyword%"];
        }
        $dataList = $this->mod::where($map)->append(['recommends_name','admin_id_name'])->order('id', 'desc')->paginate($limit, false, ['page' => $page, 'query' => ['keyword' => $keyword]]);
        return $this->success('获取成功', $dataList);
    }

    public function read ($id=0){
        $res=$this->mod::where('id',$id)->append(['recommends_name','admin_id_name'])->find();
        //推荐数据
        $res['recommends_data'] = \app\admin\model\Classify::where('pid',127)->field('id,title')->select();
        return $this->success('ok',$res);
    }

    public function save()
    {
        $data = $this->request->param();
        try {
            //验证
            $valCheck = validate(CheckArticle::class)->check($data);
            if ($valCheck !== true) {
                return $this->error($valCheck);
            }
        } catch (ValidateException $e) {
            return $this->error($e->getError());
        }
        $data['admin_id'] = $this->request->uid;
        if ($this->mod::create($data)) {
            return $this->success('添加成功');
        } else {
            return $this->error('添加失败');
        }
    }
    public function edit()
    {
        $data = $this->request->param();
        try {
            //验证
            $valCheck = validate(CheckArticle::class)->scene('edit')->check($data);
            if ($valCheck !== true) {
                $this->error($valCheck);
            }
        } catch (ValidateException $e) {
            return $this->error($e->getError());
        }
        if ($this->mod::update($data)) {

            return $this->success('编辑成功');
        } else {
            return $this->error('编辑失败');
        }
    }
    public function delete()
    {
        $id = $this->request->param('id/d');
        if (!$id) {
            return $this->error('参数错误');
        } else {
            if ($this->mod::destroy($id)) {
                return $this->success('删除成功');
            } else {
                return $this->error('删除失败');
            }
        }
    }
}
    